import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/cert.dart';
import 'package:kxy_flutter_app/view/my/basic_info/cert_item_widget.dart';
import 'package:kxy_flutter_app/view/root/view_model/navigation_model.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'cert_detail_view.dart';

class CertListView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CertListViewState();
  }
}

class CertListViewState extends State<CertListView> {
  List<CertProfile> certProfileList;
  RefreshController controller = new RefreshController();
  Future loadFuture;

  @override
  void initState() {
    loadFuture = loadList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('证件管理'),
        actions: [
          FlatButton(
            child: Text('新增'),
            textColor: Theme.of(context).primaryColor,
            onPressed: gotoDetail,
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: FutureBuilder(
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return createListBody();
          } else {
            return LoadingWidget();
          }
        },
        future: loadFuture,
      ),
    );
  }

  Widget createListBody() {
    if (certProfileList.length == 0) {
      return EmptyWidget(onRefresh: loadList);
    }
    return SmartRefresher(
      controller: controller,
      enablePullDown: true,
      enablePullUp: false,
      header: RefreshHeader(),
      child: listview(),
      onRefresh: () async {
        await loadList();
        controller.refreshCompleted();
      },
    );
  }

  Widget listview() {
    return ListView.builder(
      padding: EdgeInsets.all(20),
      itemCount: certProfileList.length,
      itemBuilder: (cxt, index) {
        var item = certProfileList[index];
        return GestureDetector(
          child: CertItemWidget(certProfile: item, index: index),
          onTap: () => gotoDetail(certId: item.id),
          onLongPress: () => confirmRemove(item),
        );
      },
    );
  }

  Future confirmRemove(CertProfile cert) async {
    var confirm = await showDialog(
        context: context,
        builder: (cxt) {
          return AlertDialog(
            title: Text('提示'),
            content: Text('您确认删除证件吗？'),
            actions: [
              FlatButton(
                child: Text('取消'),
                onPressed: () => Navigator.pop(context, false),
              ),
              FlatButton(
                child: Text('确认'),
                onPressed: () => Navigator.pop(context, true),
              ),
            ],
          );
        });

    if (confirm == true) {
      await remove(cert.id);
      await loadList();
    }
  }

  Future gotoDetail({String certId}) async {
    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (cxt) => CertDetailView(certId: certId),
      ),
    );
    var navModel = Provider.of<NavigationModel>(context, listen: false);
    navModel.refreshNoticeCount();
    setState(() {
      this.loadList();
    });
  }

  Future loadList() async {
    var res = await Http.instance.post(
      '/usercenter-app/cert/getcertlistbyuserid',
      params: <String, dynamic>{'userId': Auth.instance.userId},
    );

    if (res.code == 200) {
      setState(() {
        certProfileList = (res.data as List).map((x) {
          return CertProfile.fromJson(x);
        }).toList();
      });
    } else {
      certProfileList = [];
      Fluttertoast.showToast(msg: res.msg);
    }
  }

  Future remove(String id) async {
    var res = await Http.instance.post(
      '/usercenter-app/cert/deletebyid',
      params: {'id': id},
    );
    if (res.code == 200) {
      return res.data;
    }
    return false;
  }
}
